package cn.mazexal.examapi.common.models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author: Mazexal
 * Date: 2025/5/11
 */

public class PagedResponse<T> extends Response {
    private static final long serialVersionUID = 1L;
    private Collection<T> data;
    private int total;
    private int pageSize;
    private int current;

    public PagedResponse() {
    }

    public List<T> getData() {
        if (null == this.data) {
            return Collections.emptyList();
        } else {
            return (List)(this.data instanceof List ? (List)this.data : new ArrayList(this.data));
        }
    }

    public void setData(Collection<T> data) {
        this.data = (Collection)(null == data ? Collections.emptyList() : data);
    }

    public int getTotal() {
        return this.total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getPageSize() {
        return Math.max(this.pageSize, 1);
    }

    public void setPageSize(int pageSize) {
        this.pageSize = Math.max(pageSize, 1);
    }

    public int getCurrent() {
        return this.current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }

    public int getPageCount() {
        return this.total % this.pageSize == 0 ? this.total / this.pageSize : this.total / this.pageSize + 1;
    }

    public static <T> PagedResponse<T> success() {
        PagedResponse<T> response = new PagedResponse();
        response.setSuccess(true);
        return response;
    }

    public static <T> PagedResponse<T> error(String code, String message) {
        PagedResponse<T> response = new PagedResponse();
        response.setSuccess(false);
        response.setErrCode(code);
        response.setErrMessage(message);
        return response;
    }

    public static <T> PagedResponse<T> error(ResponseError error) {
        return error(error.getCode(), error.getMessage());
    }

    public static <T> PagedResponse<T> of(Collection<T> data, int total, int pageSize, int current) {
        PagedResponse<T> response = new PagedResponse();
        response.setSuccess(true);
        response.setData(data);
        response.setTotal(total);
        response.setPageSize(pageSize);
        response.setCurrent(current);
        return response;
    }

    public static <T> PagedResponse<T> of(int pageSize, int current) {
        return of(Collections.emptyList(), 0, pageSize, current);
    }

    public static <T> PagedResponse<T> of(PagedData<T> pagedData) {
        PagedResponse<T> pagedResponse = new PagedResponse();
        pagedResponse.setCurrent(pagedData.getCurrent());
        pagedResponse.setPageSize(pagedData.getPageSize());
        pagedResponse.setTotal(pagedData.getTotal());
        pagedResponse.setData(pagedData.getData());
        pagedResponse.setSuccess(true);
        return pagedResponse;
    }
}
